//
//  BHCirclePublishViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/9.
//  发布圈子内容

import UIKit
import AMapSearchKit

class BHCirclePublishViewController: BHBaseViewController {

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        let view = UICollectionView.buildCollectionView(layout: layout)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight)
        view.backgroundColor = .white
        view.delegate = self
        view.dataSource = self
        
        return view
    }()
    
    
    lazy var publishBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.backgroundColor = .color_34CE98
        btn.setTitle("发布", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
        btn.addTarget(self, action: #selector(publishNewCircleAct), for: .touchUpInside)
        btn.addLayerCorner(12, 0, .white)
        return btn
    }()
    
    lazy var serviceManager: BHCircleServiceManager = {
        let manager = BHCircleServiceManager.init()
        return manager
    }()
    
    
    var activityId: String = "" // 有id的时候就是活动的发布
    var addImageArray: [BHImageOrVideoModel] = []
    var imageUrls: [String] = []
    var videoModel: BHImageOrVideoModel?
    fileprivate var type: Int = 0  // 0默认选择的是照片  1选择的是视频
    fileprivate var publishTitle: String = ""
    fileprivate var publishContent: String = ""
    fileprivate var videoCoverUrl: String = ""
    fileprivate var userColumnArray: [BHCircleColumnModel] = []
    fileprivate var userColumnTextArray: [String] = []
    fileprivate var choseColunmModel: BHCircleColumnModel?
    fileprivate var relationModel: BHCirclePublishRelationInfoModel?
    fileprivate var relationAreaPoi: AMapPOI?
    override func viewDidLoad() {
        super.viewDidLoad()

        self.resortLevel()
        self.bh_navigationBar.title_label.text = "发布"
        
        self.publishBtn.frame = CGRect(x: UIScreen.width-50-16, y: UIScreen.stateBarHeight+10, width: 50, height: 24)
        self.bh_navigationBar.addSubview(self.publishBtn)
        

        self.registerCell()
        self.view.addSubview(self.collectionView)
        if self.videoModel != nil {
            self.type = 1
        }
        
        self.loadPersonalColumn()
        self.serviceManager.requestSelfColumnService()
    }
    
    private func registerCell() {
        self.collectionView.regiseterNib(nibName: "BHCirclePublishTextCell")
        self.collectionView.regiseterNib(nibName: "BHCircleContentTextCell")
        self.collectionView.regiseterNib(nibName: "BHCirclePublishImageAddCell")
        self.collectionView.regiseterNib(nibName: "BHCircleMoreChoseCell")
        self.collectionView.regiseterNib(nibName: "BHCircleRelationCollectionViewCell")
        self.collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "bh_space_for_image_andChose_header")
    }
    
    private func resortLevel() {
        var tempArray = self.navigationController?.viewControllers
        for (index, vc) in self.navigationController!.viewControllers.enumerated() {
            if vc is BHCircleChoseImageOrVideoViewController {
                tempArray?.remove(at: index)
                break
            }
        }
        self.navigationController?.viewControllers = tempArray!
    }

    private func choseColumn() {
        if self.userColumnTextArray.count == 0 {
            for model in self.userColumnArray {
                self.userColumnTextArray.append(model.name)
            }
        }
        BHCommonTool.showSheetWith(showVC: self, title: "选择栏目", messages: self.userColumnTextArray) { (index) in
            if index != -1 { // 不是取消
                self.choseColunmModel = self.userColumnArray[index]
                self.collectionView.reloadData()
            }
        }
    }
    
    @objc func publishNewCircleAct() {
        self.checkUpParamters()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
}

extension BHCirclePublishViewController: BHCircleChoseImageOrVideoViewControllerProtocol {
    func didChoseImageActHandler(images: [BHImageOrVideoModel]) {
        self.addImageArray = images
        if self.addImageArray.count != 0 {
            self.type = 0
        }
        self.collectionView.reloadData()
    }
    func didChoseVideoActHandler(videoModel: BHImageOrVideoModel?) {
        self.videoModel = videoModel
        if videoModel != nil {
            self.type = 1
        }
        self.collectionView.reloadData()
    }
}

// 关联场馆、赛事、趣玩 && 选择地址
extension BHCirclePublishViewController: BHCircleChoseRelationViewControllerDelegate,BHCircleChosePlaceAreaViewControllerDelegate {
    func didChoseRelation(model: BHCirclePublishRelationInfoModel) {
        self.relationModel = model;
        self.collectionView.reloadData()
    }
    
    func didChoseAddress(poi: AMapPOI?) {
        self.relationAreaPoi = poi
        self.collectionView.reloadData()
    }
}


extension BHCirclePublishViewController: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if scrollView == self.collectionView{
            self.collectionView.isScrollEnabled = true
        }else {
            self.collectionView.isScrollEnabled = false
        }
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        if self.activityId.isEmpty == false {
            return 2
        }
        return 3
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return 2
        }else if section == 1 {
            if self.type == 0 {
                if self.addImageArray.count < 9 {
                    return self.addImageArray.count+1
                }else {
                    return self.addImageArray.count
                }
            }else {
                if self.videoModel != nil { // 多给一个占位
                    return 2
                }
                return 1
            }
        }else {
            return 3
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                return CGSize(width: UIScreen.width, height: 45)
            }else {
                return CGSize(width: UIScreen.width, height: 145)
            }
        }else if indexPath.section == 1 {
            if self.videoModel != nil {
                let wi = (UIScreen.width-32-5)/2.0
                return CGSize(width: wi-0.5, height: wi)
            }else {
                let wi = (UIScreen.width-32-10)/3.0
                return CGSize(width: wi-0.2, height: wi)
            }
            
        }else {
            if indexPath.row == 1 {
                if self.relationModel != nil {
                    return CGSize(width: UIScreen.width, height: 150)
                }
            }
            return CGSize(width: UIScreen.width, height: 50)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if section == 1 {
            return UIEdgeInsets(top: 0, left: 16, bottom: 20, right: 16)
        }else {
            return .zero
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        if section == 1 {
            return 10
        }else {
            return 0
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        if section == 1 {
            return 5
        }else {
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if section == 2 {
            return CGSize(width: UIScreen.width, height: 10)
        }else {
            return .zero
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.view.endEditing(true)
        if indexPath.section == 1 {
        
            if self.type == 0 {
                if indexPath.row == self.addImageArray.count {
                    
                    let addSourceVC = BHCircleChoseImageOrVideoViewController.init()
                    if self.addImageArray.count == 0 {
                        addSourceVC.choseType = 0
                    }else {
                        addSourceVC.choseType = 1
                    }
                    addSourceVC.entryType = 1
                    addSourceVC.delegate = self
                    self.navigationController?.pushViewController(addSourceVC, animated: true)
                    
                }else { // 预览
                    BHMediaTool.showPreview(array: self.addImageArray, current: indexPath.row)
                }
            }else {
                if indexPath.row == 1 { // 占位用的
                    return
                }
                if self.videoModel == nil {
                    let addSourceVC = BHCircleChoseImageOrVideoViewController.init()
                    addSourceVC.choseType = 0
                    addSourceVC.entryType = 1
                    addSourceVC.delegate = self
                    self.navigationController?.pushViewController(addSourceVC, animated: true)
                }else {
                    BHMediaTool.previewVideo(model: self.videoModel!)
                }
            }
        }
        
        if indexPath.section == 2 {
            if indexPath.row == 0 { // 选栏目
                self.choseColumn()
            }
            if indexPath.row == 1 {
                let relationVC = BHCircleChoseRelationViewController.init()
                relationVC.delegate = self
                self.navigationController?.pushViewController(relationVC, animated: true)
            }
            
            if indexPath.row == 2 {
                let areaVC = BHCircleChosePlaceAreaViewController.init()
                areaVC.weakSuper = self
                areaVC.delegate = self
                self.navigationController?.pushViewController(areaVC, animated: true)
                
            }
        }
    }
}
extension BHCirclePublishViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.section == 0 {
            return self.cellForText(indexPath: indexPath)
        }else if indexPath.section == 1 {
            return self.cellForImage(indexPath: indexPath)
        }else {
            return self.cellForChose(indexPath: indexPath)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "bh_space_for_image_andChose_header", for: indexPath)
        view.backgroundColor = .color_f5f5f5
        view.clipsToBounds = true
        return view
    }
}

extension BHCirclePublishViewController {
    func cellForText(indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.row == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHCirclePublishTextCell", for: indexPath) as! BHCirclePublishTextCell
            cell.textFiledEndEditingBlock = {[weak self] text in
                self?.publishTitle = text
            }
            return cell
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHCircleContentTextCell", for: indexPath) as! BHCircleContentTextCell
            cell.textViewBegainEditingBlock = { [weak self] in
                self?.collectionView.isScrollEnabled = false
            }
            cell.textViewDidEndEditingBlock = {[weak self] text in
                self?.publishContent = text
                self?.collectionView.isScrollEnabled = true
            }
            return cell
        }
    }
    
    
}


extension BHCirclePublishViewController {
    func cellForImage(indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHCirclePublishImageAddCell", for: indexPath) as! BHCirclePublishImageAddCell
        if self.type == 1 { // 视频
            if indexPath.row == 0 {
                cell.model = self.videoModel
            }else {
                cell.imageBtn.isHidden = true
                cell.delBtn.isHidden = true
            }
        }else {
            if indexPath.row < self.addImageArray.count {
                cell.model = self.addImageArray[indexPath.row]
            }else {
                cell.model = nil
            }
        }
        cell.deleteChoseImageBlock = { [weak self] in
            if self?.videoModel != nil {
                self?.videoModel = nil
            }else {
                self?.addImageArray.remove(at: indexPath.row)
            }
            self?.collectionView.reloadData()
        }
        return cell
    }
}

extension BHCirclePublishViewController {
    func cellForChose(indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.row == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHCircleMoreChoseCell", for: indexPath) as! BHCircleMoreChoseCell
            cell.name_label.text = "选择栏目"
            cell.chose_btn.setTitle("请选择栏目 ", for: .normal)
            cell.chose_btn.isSelected = self.choseColunmModel != nil
            cell.chose_btn.setTitle("\(self.choseColunmModel?.name ?? "") ", for: .selected)
            return cell
        }else if indexPath.row == 1 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHCircleRelationCollectionViewCell", for: indexPath) as! BHCircleRelationCollectionViewCell
            cell.model = self.relationModel
            // 删除
            cell.deleteBtn.addBtnAction(action: {[weak self] (_) in
                BHCommonTool.showAlertWith(showVC: nil, title: nil, message: "是否删除关联？", okBtn: "确定", cancel: "取消") { (confirm) in
                    if confirm == true {
                        self?.relationModel = nil
                        self?.collectionView.reloadData()
                    }
                }
            }, for: .touchUpInside)
            return cell
        }
        else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHCircleMoreChoseCell", for: indexPath) as! BHCircleMoreChoseCell
            cell.name_label.text = "位置"
            cell.chose_btn.setTitle("请选择 ", for: .normal)
            cell.chose_btn.isSelected = self.relationAreaPoi != nil
            cell.chose_btn.setTitle("\(self.relationAreaPoi?.name ?? "") ", for: .selected)
            return cell
        }
    }
}


// MARK: 获取数据
extension BHCirclePublishViewController {
    func loadPersonalColumn()  {
        // 返回个人栏目
        self.serviceManager.circleColumnResponseForUserBlock = { [weak self] userColumnArray in
            self?.userColumnArray = userColumnArray
        }
    }
}

// MARK: 发布之前的校验
extension BHCirclePublishViewController {
    func checkUpParamters()  {
        if self.publishTitle.isEmpty == true {
            BHToast.toast(text: "请填写标题")
            return
        }
        
        if self.publishContent.isEmpty == true {
            BHToast.toast(text: "请填写内容")
            return
        }
        
        if self.addImageArray.count == 0 && self.videoModel == nil { // 没有选择图片和视频
            BHToast.toast(text: "请选择您要上传的图片或者视频")
            return
        }
        
        if self.type == 1 { // 视频
            self.tranData()
        }else { // 图片
            self.uploadImages()
        }
    }
}


// MARK: 上传图片
extension BHCirclePublishViewController  {
    func uploadImages()  {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        let images: [UIImage] = BHImageOrVideoModel.transeToImage(array: self.addImageArray)
        manager.upload(images: images, progressHandler: nil) { (success, errorMsg, urls) in
            if success == true {
                self.imageUrls = urls
                self.publishCircleService()
            }else {
                SVProgressHUD.dismiss()
                BHToast.toast(text: errorMsg)
            }
        }
    }
}

// MARK: 上传视频
extension BHCirclePublishViewController  {
    func tranData() {
        SVProgressHUD.show()
        self.videoModel!.transToVideoData {[weak self] (data) in
            if data != nil {
                self?.uploadVideo(data: data!)
            }else {
                SVProgressHUD.dismiss()
                BHToast.toast(text: "资源转换出错，请稍后重试")
            }
        }
    }
    
    func uploadVideo(data: Data) {
        let manager = BHHTTPClient.init()
        manager.uploadVideo(data: data, progressHandler: nil) { (success, errorMsg, url,cover) in
            if success == true {
                self.videoModel?.videoUrl = url
                self.videoCoverUrl = cover
                self.publishCircleService()
            }else {
                SVProgressHUD.dismiss()
                BHToast.toast(text: errorMsg)
            }
        }
    }
}

// MARK: 发布接口
extension BHCirclePublishViewController  {
    func publishCircleService()  {
        SVProgressHUD.show()
        let dic = self.appendPublishDic()
        let manager = BHHTTPClient.init()
        manager.post(url: String.circle_publish_url, paramters: dic) { (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                BHToast.toast(text: "发布成功")
                NotificationCenter.default.post(name: NSNotification.Name.init(String.addNewCircleRefreshKey), object: nil)

                DispatchQueue.main.asyncAfter(deadline: .now()+1) {
                    self.navigationController?.popViewController(animated: true)
                }
               
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
    
    func appendPublishDic() -> [String:Any] {
        var dic: [String: Any] = [:]
        dic["title"] = self.publishTitle
        dic["content"] = self.publishContent
        if self.type == 1 { // 视频
            dic["resourceType"] = 2
            dic["urlList"] = [self.videoModel?.videoUrl ?? ""]
            dic["extraUrl"] = self.videoCoverUrl
        }else { // 图片
            dic["resourceType"] = 1
            dic["urlList"] = self.imageUrls
        }
        if self.activityId.isEmpty == true {
            dic["circleColumnId"] = self.choseColunmModel?.columnId
        }else {
            dic["circleColumnId"] = self.activityId
        }
        dic["relationType"] = self.relationModel?.type
        dic["relationId"] = self.relationModel?.relationId
        dic["place"] = self.relationAreaPoi?.name
        dic["address"] = self.relationAreaPoi?.address
        dic["latitude"] = BHLocationManager.shared.latitude
        dic["longitude"] = BHLocationManager.shared.longitude

        return dic
    }
}
